<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="成就名称" prop="achieveId">
        <el-select v-model="queryParams.achieveId" placeholder="请选择成就" clearable
                   @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in options.achieveList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择审核状态" clearable
                   @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in options.Achieve_Apply_State.list"
            v-bind="item"
            :key="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核人" prop="reviewer">
        <el-select v-model="queryParams.reviewer" placeholder="请选择审核人" filterable clearable
                   @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in options.userList"
            :value="item.userId"
            :label="item.nickName"
            :key="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请人" prop="applicant">
        <el-select v-model="queryParams.applicant" placeholder="请选择申请人" filterable clearable
                   @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in options.userList"
            :value="item.userId"
            :label="item.nickName"
            :key="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="AchieveImproveApplicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="成就" align="center" prop="achieveId">
        <template v-slot="{row}">
          {{ row.achieveId | achieveFormat }}
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="state">
        <template v-slot="{row}">
          {{ row.state | stateFormat }}
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applicant">
        <template v-slot="{row}">
          {{ row.applicant | userFormat }}
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="createTime"/>
      <el-table-column label="审核人" align="center" prop="reviewer">
        <template v-slot="{row}">
          {{ row.reviewer | userFormat }}
        </template>
      </el-table-column>
<!--      <el-table-column label="备注" align="center" prop="remark"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="currentUserId === scope.row.applicant && scope.row.state === options.Achieve_Apply_State.enums.WAIT.value" size="mini" type="text" icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     >修改
          </el-button>
          <el-button v-if="currentUserId === scope.row.reviewer && scope.row.state === options.Achieve_Apply_State.enums.WAIT.value" size="mini" type="text" icon="el-icon-edit"
                     @click="handleAudit(scope.row)"
                     v-hasPermi="['base:AchieveImproveApplication:audit']">审核
          </el-button>
          <el-button v-if="(currentUserId === scope.row.applicant || currentUserId === scope.row.reviewer)" size="mini"
                     type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改等级申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="成就" prop="achieveId">
              <el-select :disabled="isAudit" v-model="form.achieveId" placeholder="请选择成就" style="width: 320px"
                         filterable clearale>
                <el-option
                  v-for="item in options.achieveList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人" prop="applicant">
              <el-select :disabled="isAudit" v-model="form.applicant" placeholder="请输入申请人" style="width: 320px"
                         filterable clearale disabled>
                <el-option
                  v-for="item in options.userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核人" prop="reviewer">
              <el-select v-model="form.reviewer" :disabled="isAudit" placeholder="请输入审核人" style="width: 320px"
                         filterable clearale>
                <el-option
                  v-for="item in options.userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isAudit">
          <el-col :span="12">
            <el-form-item label="审核" prop="state">
              <el-switch
                v-model="form.state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="options.Achieve_Apply_State.enums.PASS.value"
                :inactive-value="options.Achieve_Apply_State.enums.REJECT.value"
                active-text="通过"
                inactive-text="不通过">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addAchieveImproveApplication,
  delAchieveImproveApplication,
  getAchieveImproveApplication,
  listAchieveImproveApplication,
  updateAchieveImproveApplication
} from "@/api/system/AchieveImproveApplication";
import {listUser} from "@/api/system/user";
import {listSysAchieve} from "@/api/system/SysAchieve";
import {Achieve_Apply_State} from '@/views/train/Enums'
import {mapGetters} from "vuex";
import {isValid} from "@/utils/validate";
import mixins from "@/views/train/mixins";

let _this = null
export default {
  name: "AchieveImproveApplication",
  mixins: [mixins],
  filters: {
    achieveFormat(achieveId) {
      return (_this.options.achieveList.find(e => e.id === achieveId) || {}).name
    },
    userFormat(userId) {
      return (_this.options.userList.find(e => e.userId === userId) || {}).nickName
    },
    stateFormat(value) {
      return _this.options.Achieve_Apply_State.map[value]
    }
  },
  computed: {
    ...mapGetters(['currentUserId'])
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 等级申请表格数据
      AchieveImproveApplicationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 成就
        achieveId: null,
        // 申请人
        applicant: null,
        // 状态
        state: null,
        // 审核人
        reviewer: null,
        delBy: null,
        delTime: null,
      },
      // 表单参数
      form: {},
      isAudit: false,
      // 表单校验
      rules: {
        achieveId: [
          {required: true, message: "成就不能为空", trigger: "blur"}
        ],
        applicant: [
          {required: true, message: "申请人不能为空", trigger: "blur"}
        ],
        reviewer: [
          {required: true, message: "审核人不能为空", trigger: "blur"}
        ],
      },
      options: {
        userList: [],
        achieveList: [],
        Achieve_Apply_State: Achieve_Apply_State,
      }
    };
  },
  methods: {
    // 数据初始化
    initData() {
      // 获取人员列表
      listUser().then(res => {
        this.options.userList = res.rows || []
      })
      listSysAchieve().then(res => {
        this.options.achieveList = res.rows || []
      })


      // 获取成就列表
    },
    /** 查询等级申请列表 */
    getList() {
      this.loading = true;
      listAchieveImproveApplication(this.doSort(this.queryParams)).then(response => {
        this.AchieveImproveApplicationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        state: null,
        reviewer: null,
        applicant: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.state = this.options.Achieve_Apply_State.enums.WAIT.value
      this.form.applicant = this.currentUserId
      this.isAudit = false
      this.open = true;
      this.title = "添加等级申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAchieveImproveApplication(id).then(response => {
        this.form = response.data;
        // 修改的时候状态理论上为待审核...
        if (!isValid(this.form.state)) {
          this.form.state = this.options.Achieve_Apply_State.enums.WAIT.value
        }
        this.open = true;
        this.isAudit = false
        this.title = "修改";
      });
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      this.reset();
      const id = row.id || this.ids
      getAchieveImproveApplication(id).then(response => {
        this.form = response.data;
        // 审核时默认状态是审核通过
        this.form.state = this.options.Achieve_Apply_State.enums.PASS.value
        this.open = true;
        this.isAudit = true
        this.title = "审核";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAchieveImproveApplication(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAchieveImproveApplication(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('确认删除？').then(function () {
        return delAchieveImproveApplication(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/AchieveImproveApplication/export', {
        ...this.queryParams
      }, `AchieveImproveApplication_${new Date().getTime()}.xlsx`)
    },
    init() {
      this.initData()
      this.getList()
    },
  },
  created() {
    _this = this
    this.init();
  },
};
</script>
